package com.meilai.project.util;

import com.meilai.project.exception.CommonException;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;

@Component
public class XmlUtil {

    public static String getXmlInfo() {
        StringBuilder sb = new StringBuilder();
        sb.append("<videoSend>");
        sb.append("    <header>");
        sb.append("        <sid>1</sid>");
        sb.append("        <type>service</type>");
        sb.append("    </header>");
        sb.append("    <service name=\"videoSend\">");
        sb.append("        <fromNum>0000021000011001</fromNum>");
        sb.append("           <toNum>33647405</toNum>");
        sb.append("        <videoPath>mnt/5.0.217.50/resources/80009.mov</videoPath>");
        sb.append("        <chargeNumber>0000021000011001</chargeNumber>");
        sb.append("    </service>");
        sb.append("</videoSend>");
        return sb.toString();
    }

    public static String testInterface(String reqPath, String reqXml){
        try{

            Encoder encoder = Base64.getEncoder();

            URL reqURL = new URL(reqPath);
            HttpURLConnection conn   = (HttpURLConnection) reqURL.openConnection();
            conn.setRequestMethod("POST");
            //设置发送数据
            conn.setDoOutput(true);
            conn.setRequestProperty("Accept", "text/plain");
//            System.out.println("请求报文：[" + reqXml + "]");
            reqXml = reqXml.replaceAll("\\r", "").replaceAll("\\n", "");
            reqXml = encoder.encodeToString(reqXml.getBytes());

            byte[] bytes = reqXml.getBytes("UTF-8");
            conn.getOutputStream().write(bytes);

            InputStream resInput = conn.getInputStream();
            //定义字节数组
            byte[] b = new byte[1024];

            //定义一个输出流存储接收到的数据
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            //开始接收数据
            int len = 0;
            while (true) {
                len = resInput.read(b);
                if (len == -1) {
                    //数据读完
                    break;
                }
                byteArrayOutputStream.write(b, 0, len);
            }
            //从输出流中获取读取到数据(服务端返回的)
            String response = byteArrayOutputStream.toString();

            Decoder decoder = Base64.getDecoder();
//            System.out.println("返回报文的xml形式"+ new String(decoder.decode(response)));
            return org.json.XML.toJSONObject(new String(decoder.decode(response))).toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new CommonException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommonException(e.getMessage());
        }
    }

}
